package com.example.sockjs.controller;

import com.example.sockjs.entity.MyMessage;
import com.example.sockjs.interceptor.SessionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.time.LocalDate;

/**
 * @Author hezhan
 * @Date 2019/9/24 17:28
 */
@RestController
public class StompController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/message")
    public void subscription(MyMessage message, Principal principal){
        MyMessage msg = new MyMessage(message.getMessage(), message.getDatetime(), message.getFrom(), message.getTo());
        simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/queue", msg);
        System.out.println(principal.getName() + "发送了一条消息给：" + message.getTo());
    }

    @GetMapping("/sendMsg")
    public void sendMsg(String name, String message){
        MyMessage msg = new MyMessage(message, LocalDate.now().toString(), "管理员", "void");
        simpMessagingTemplate.convertAndSendToUser(name, "/queue", msg);
    }
    
    /*
     * 心跳检测 直接给源路径返回"pang"作标志
     */
    @MessageMapping("/heartBeat")
    public void heartBeat(){
        simpMessagingTemplate.convertAndSend("pang");
    }
}
